package com.example.duomeiti;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Mp4Activity extends AppCompatActivity {
    MediaPlayer mediaPlayer;
    SurfaceView mSurfaceView;
    Button play,stop,pause;
    String path;
    SurfaceHolder sh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mp4);
        play=findViewById(R.id.play);
        pause=findViewById(R.id.pause);
        stop=findViewById(R.id.stop);
        mSurfaceView=findViewById(R.id.surfaceView);
        //装载视频文件
        mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.movie);
        mediaPlayer.setLooping(true);
        //播放按钮事件
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //播放按钮事件
                try{
                    sh=mSurfaceView.getHolder();//获取播放电影的容器
                    mediaPlayer.setDisplay(sh);//把电影显示到屏幕上
                    mediaPlayer.start();
                    play.setEnabled(false); //把播放按钮设置为变灰
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        //暂停按钮事件
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if(!mediaPlayer.isPlaying()){   //没有播放
                        mediaPlayer.start();        //播放
                        pause.setText("暂停");
                    }else{
                        mediaPlayer.pause();        //暂停
                        pause.setText("播放");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        //停止按钮事件
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                //装载视频文件
                mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.movie);
                mediaPlayer.setLooping(true);
                play.setEnabled(true);//把播放按钮恢复
            }
        });
    }
}
